<template>
  <div id="gongcheng">
    <div
      v-if="loginurl"
      class="my-iframe"
    >
      <iframe
        allow="fullscreen"
        referrerpolicy="no-referrer-when-downgrade"
        sandbox="allow-same-origin allow-scripts allow-forms"
        :src="loginurl"
        width="100%"
      ></iframe>
      <!-- src="http://112.103.254.249:21146/gitea/test" -->
    </div>
    <div class="all-tab">
      <div
        v-for="(item, index) in labels"
        :key="index"
        :class="{active: active === index}"
        @click="handleNavItemClick(index,item)"
      >
        {{ item.bookName }}
      </div>
    </div>
    <div class="step-one">
      <div class="all-title">
        <div class="two-search">
          <div class="search-left">
            <div>项目信息：</div>
            <el-input
              v-model="searchValue"
              clearable
              style="width: 360px"
              placeholder="请输入"
            />
            <div
              class="all-btn"
              @click="getList"
            >搜索</div>
          </div>
          <div
            v-if="active === 1 && role != 2"
            class="all-btn right-btn"
            @click="dialogInfo = true"
          >
            <el-icon>
              <Tickets />
            </el-icon>
            我的信息
          </div>
          <div
            v-if="active === 1"
            class="all-btn right-btn2"
            @click="handleAdd"
          >
            <el-icon>
              <CirclePlus />
            </el-icon>
            添加项目
          </div>
        </div>
      </div>
      <!-- 精品项目 -->
      <div
        v-if="activeType === 1"
        class="step-one-content"
      >
        <div
          v-for="item in list"
          :key="item.title"
          class="all-box"
          @click="goDetail(item)"
        >
          <div class="one-title">{{ item.name }}</div>
          <div class="one-content">{{ item.description }}</div>
          <div class="one-time">{{ item.time }}</div>
          <div
            v-if="role != 2"
            class="one-btns"
          >
            <div
              v-if="item.top === 0"
              @click.stop="setStatus(item.id, 1)"
            >
              <el-icon>
                <Upload />
              </el-icon>
              置顶
            </div>
            <div
              v-if="item.top >= 1"
              @click.stop="setStatus(item.id, 1)"
            >
              <el-icon>
                <CircleClose />
              </el-icon>
              取消置顶
            </div>
            <div
              v-if="item.status === 1"
              @click.stop="setStatus(item.id, 2)"
            >
              <el-icon>
                <View />
              </el-icon>
              隐藏项目
            </div>
            <div
              v-if="item.status === 2"
              @click.stop="setStatus(item.id, 2)"
            >
              <el-icon>
                <Hide />
              </el-icon>
              取消隐藏
            </div>
          </div>
          <div class="one-brand">
            <div
              v-show="item.top === 0"
              class="shixun-brand"
            >实训项目</div>
            <div
              v-show="item.top >= 1"
              class="good-brand"
            >精品项目</div>
          </div>
        </div>
      </div>
      <!-- 我的项目 -->
      <div
        v-if="activeType === 2"
        class="step-one-content"
      >
        <div
          v-for="item in list"
          :key="item.title"
          class="all-box"
          @click="goDetail(item)"
        >
          <div
            v-if="item.importStatus == 2"
            class="mask-loading"
          >
            <p>正在创建项目，时间较长，请耐心等待...</p>
          </div>
          <div class="one-title">{{ item.name }}</div>
          <div class="one-content">{{ item.description }}</div>
          <div class="one-time">{{ item.time }}</div>
          <div class="one-btns">
            <div @click.stop="handleEdit(item)">
              <el-icon>
                <Edit />
              </el-icon>
              修改
            </div>
            <div @click.stop="handleDelete(item)">
              <el-icon>
                <Close />
              </el-icon>
              删除
            </div>
          </div>
          <div class="one-brand">
            <div class="my-brand">我的项目</div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      v-model="dialogVisible"
      width="630"
      :before-close="handleClose"
    >
      <div class="my-dialog">
        <div class="my-dialog-tab">
          <div
            :class="{active: form.type === 1,disabled:isEdit === true}"
            @click="changeTab(1)"
          >创建项目</div>
          <div
            :class="{active: form.type === 2,disabled:isEdit === true}"
            @click="changeTab(2)"
          >导入gitee/github</div>
        </div>
        <div class="my-dialog-content">
          <div v-if="form.type === 2">
            <div class="item-label">挑选项目：</div>
            <div class="item-content">
              <div class="tiao-box">
                <a
                  href="https://github.com/"
                  target="_blank"
                >
                  <img src="@/assets/img/github.png" />
                </a>
                <a
                  href="https://gitee.com/explore/"
                  target="_blank"
                >
                  <img src="@/assets/img/gitee.png" />
                </a>
              </div>
            </div>
          </div>
          <div>
            <div class="item-label"><span class="red">*</span>项目名称：</div>
            <div class="item-content">
              <el-input
                v-model="form.name"
                @blur="getCangkuName"
              ></el-input>
            </div>
          </div>
          <div>
            <div class="item-label"><span class="red">*</span>仓库名称：</div>
            <div class="item-content">
              <el-input
                v-model="form.repositroyName"
                :disabled="isEdit"
              ></el-input>
            </div>
          </div>
          <div class="flex-start">
            <div class="item-label"><span class="red">*</span>项目简介：</div>
            <div class="item-content">
              <el-input
                v-model="form.description"
                type="textarea"
                rows="6"
              ></el-input>
            </div>
          </div>
          <div v-if="form.type === 2">
            <div class="item-label"><span class="red">*</span>链接地址：</div>
            <div class="item-content">
              <el-input
                v-model="form.url"
                :disabled="isEdit"
                placeholder="以 https:// 开头，必须以 .git 结尾"
              ></el-input>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="isEdit"
            color="#155EEF"
            @click="editAgent()"
          >
            修改
          </el-button>
          <el-button
            v-else
            color="#155EEF"
            @click="addAgent()"
          >
            确定
          </el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogInfo"
      width="630"
    >
      <div class="my-dialog">
        <div class="dialog-info">
          <div>
            为方便你顺利接入代码管理平台，我们已为您准备好了专属的 Git 账号信息，用于代码仓库的登录与管理。请妥善保管你的账号信息。
          </div>
          <br />
          <div>
            账号：{{ userNumber }}
          </div>
          <div>
            密码：a123456789
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            color="#155EEF"
            @click="dialogInfo = false"
          >好的</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { h } from "vue";

export default {
  data() {
    return {
      timer: null,
      userNumber: "",
      dialogInfo: false,
      role: 0,
      isEdit: false,
      loginurl: "",
      logouturl: "",
      dialogVisible: false,
      searchValue: "",
      labels: [
        {
          id: 1,
          bookName: "所有项目",
        },
        {
          id: 2,
          bookName: "我的项目",
        },
      ],
      active: 0,
      activeType: 1,
      list: [],
      form: {
        name: "",
        repositroyName: "",
        description: "",
        //1创建项目2导入gitee/github
        type: 1,
        url: "",
      },
    };
  },
  created() {
    this.getUserInfo();
    this.getLoginPage();
    this.getList();
  },
  beforeUnmount() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  },
  methods: {
    getLogouturl() {
      this.logouturl1 = this.logouturl;
    },
    getUserInfo() {
      const userInfo = localStorage.getItem("userInfo");
      const { role } = JSON.parse(userInfo);
      this.role = role;
      console.log(role);
    },
    getCangkuName() {
      const url = `/tes/project/pinyin`;
      if (this.isEdit) {
        return;
      }
      const data = {
        name: this.form.name,
      };
      this.$axios
        .post(url, data)
        .then((response) => {
          const res = response.data;
          this.form.repositroyName = res;
        })
        .finally(() => {});
    },
    getLoginPage() {
      const url = `/tes/project/gitea-url`;
      this.$axios
        .get(url)
        .then((response) => {
          const res = response.data;
          const { gitBackUrl } = res;
          const userInfo = JSON.parse(localStorage.getItem("userInfo"));
          const userNumber = userInfo.userNumber;
          if (userNumber) {
            //http://112.103.254.249:21146/gitea/auto-logout
            this.loginurl = `${gitBackUrl}/auto-login/${userNumber}/a123456789`;
            this.userNumber = userNumber;
            // this.logouturl = `${gitBackUrl}/auto-logout`;
            // this.logout(res);
          }
        })
        .finally(() => {});
    },
    changeTab(type) {
      if (this.isEdit) {
        return;
      }
      this.form.type = type;
    },
    handleDelete(row) {
      const url = `/tes/project/delete`;
      const params = {
        id: row.id,
      };
      this.$confirm("是否删除？").then(() => {
        const loading = this.$loading({
          lock: true,
          text: "删除中，请稍后...",
          background: "rgba(0, 0, 0, 0.7)",
        });
        this.$axios
          .delete(url, { params })
          .then((response) => {
            const res = response;
            this.$message.success(res.message || "删除成功");
            this.getList();
          })
          .finally(() => {
            loading.close();
          });
      });
    },
    handleEdit(row) {
      console.log(row, "row");
      this.clearForm();
      this.isEdit = true;
      this.dialogVisible = true;
      this.isEdit = true;
      this.form.name = row.name;
      this.form.description = row.description;
      this.form.type = row.type;
      this.form.id = row.id;
      this.form.repositroyName = row.reposName;
      if (row.type === 2) {
        this.form.url = row.url;
      }
    },
    clearForm() {
      this.form.name = "";
      this.form.description = "";
      this.form.type = 1;
      this.form.url = "";
      this.form.repositroyName = "";
    },
    editAgent() {
      if (this.form.name === "") {
        this.$message.error("项目名称不能为空");
        return;
      }
      if (this.form.description === "") {
        this.$message.error("项目简介不能为空");
        return;
      }
      if (this.form.type === 2 && this.form.url === "") {
        this.$message.error("链接地址不能为空");
        return;
      }
      const loading = this.$loading({
        lock: true,
        text: "加载中...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const data = this.form;
      const url = `/tes/project/update`;
      this.$axios
        .post(url, data)
        .then((response) => {
          const res = response;
          this.getList();
          this.$message.success(res.message || "操作成功");
        })
        .finally(() => {
          loading.close();
          this.dialogVisible = false;
        });
    },
    //添加项目
    addAgent() {
      if (this.form.name === "") {
        this.$message.error("项目名称不能为空");
        return;
      }
      if (this.form.description === "") {
        this.$message.error("项目简介不能为空");
        return;
      }
      if (this.form.type === 2 && this.form.url === "") {
        this.$message.error("链接地址不能为空");
        return;
      }
      const loading = this.$loading({
        lock: true,
        text: "加载中...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const data = this.form;
      const url = `/tes/project/add`;
      this.$axios
        .post(url, data)
        .then((response) => {
          const res = response;
          this.getList();
          this.$message.success(res.message || "操作成功");
          this.dialogVisible = false;
        })
        .finally(() => {
          loading.close();
        });
    },
    //置顶或隐藏
    setStatus(id, type) {
      const loading = this.$loading({
        lock: true,
        text: "加载中...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const params = {
        id: id,
        type: type,
      };
      const url = `/tes/project/topOrHide?id=${id}&type=${type}`;
      this.$axios
        .post(url)
        .then((response) => {
          const res = response;
          this.getList();
          this.$message.success(res.message || "操作成功");
        })
        .finally(() => {
          loading.close();
        });
    },
    goDetail(row) {
      if (row.importStatus == 2) {
        return;
      }
      const { gitBackUrl, userNumber, reposName } = row;
      const redirectUrl = `${gitBackUrl}/redirect-page/${userNumber}/${reposName}`;
      console.log("跳转URL:", redirectUrl);
      const win = window.open(redirectUrl, "_blank");
      if (win) {
        win.focus();
      } else {
        alert("请允许弹出窗口以跳转到目标页面。");
      }
    },
    handleNavItemClick(index, row) {
      this.active = index;
      console.log(row, "row");
      this.activeType = row.id;
      this.getList();
    },
    handleClose() {
      this.dialogVisible = false;
    },
    handleAdd() {
      this.clearForm();
      this.isEdit = false;
      this.dialogVisible = true;
    },
    // getList() {
    //   // const loading = this.$loading({
    //   //   lock: true,
    //   //   text: "加载中...",
    //   //   background: "rgba(0, 0, 0, 0.7)",
    //   // });
    //   const data = {
    //     name: this.searchValue,
    //   };
    //   const url = `/tes/project/list?type=${this.activeType}`;
    //   this.$axios
    //     .post(url, data)
    //     .then((response) => {
    //       const res = response.data;
    //       this.list = res;
    //       if (this.activeType == 2) {
    //         const hasStatus2 = this.list.some(
    //           (item) => item.importStatus === 2
    //         );
    //         console.log(hasStatus2); // true
    //         if (hasStatus2) {
    //           this.timer = setInterval(() => {
    //             this.getList();
    //           }, 1000);
    //         } else {
    //           clearInterval(this.timer);
    //         }
    //       }
    //     })
    //     .finally(() => {
    //       // loading.close();
    //     });
    // },
    getList() {
      const data = {
        name: this.searchValue,
      };
      const url = `/tes/project/list?type=${this.activeType}`;

      this.$axios
        .post(url, data)
        .then((response) => {
          const res = response.data;
          this.list = res;
          if (this.activeType == 2) {
            const hasStatus2 = this.list.some(
              (item) => item.importStatus === 2
            );
            if (hasStatus2) {
              if (!this.timer) {
                this.timer = setInterval(() => {
                  this.getList();
                }, 15000);
              }
            } else {
              if (this.timer) {
                clearInterval(this.timer);
                this.timer = null;
              }
            }
          }
        })
        .catch((error) => {
          console.error("请求失败:", error);
          if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
          }
        });
    },
  },
};
</script>
<style lang="scss" scoped>
#gongcheng {
  .my-iframe {
    position: absolute;
    top: -9999px;
    left: -9999px;
  }
  .all-box {
    position: relative;
    padding: 20px;
    box-sizing: border-box;
    cursor: pointer;
    transition: all 0.3s ease;
    &:hover {
      transform: scale(1.02);
    }
    .mask-loading {
      z-index: 1;
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.7);
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 10px;
      p {
        font-size: 14px;
        color: #fff;
      }
    }
  }
  .step-one {
    margin-bottom: 20px;
    .all-title {
      position: relative;
      .two-search {
        .search-left {
          display: flex;
          justify-content: flex-start;
          align-items: center;
          gap: 10px;
          margin-bottom: 10px;
          :deep(.el-input__inner) {
            height: 38px;
          }
        }
      }
      .right-btn {
        position: absolute;
        top: 0px;
        right: 125px;
      }
      .right-btn2 {
        position: absolute;
        top: 0px;
        right: 0;
      }
    }
    .step-one-content {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
      > div {
        position: relative;
        flex: 0 0 calc((100% - 40px) / 3);
        height: 270px;
        box-sizing: border-box;
        padding: 64px 27px 29px;
        .one-title {
          font-weight: bold;
          font-size: 18px;
          color: #457aff;
          margin-bottom: 20px;
        }
        .one-content {
          font-size: 14px;
          color: #505466;
          line-height: 24px;
        }
        .one-time {
          position: absolute;
          bottom: 29px;
          left: 27px;
          font-size: 14px;
          color: #9b9c9d;
        }
        .one-btns {
          position: absolute;
          top: 17px;
          right: 26px;
          display: flex;
          gap: 20px;
          font-size: 14px;
          color: #457aff;
          > div {
            display: flex;
            align-items: center;
            cursor: pointer;
            i {
              font-size: 18px;
            }
            &:hover {
              color: #505466;
            }
          }
        }
        .one-brand {
          position: absolute;
          top: 9px;
          left: -6px;
          .my-brand {
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 12px;
            color: #ffffff;
            width: 80px;
            height: 22px;
            background: linear-gradient(90deg, #0dbcff, #4c84ff);
            border-radius: 11px;
          }
          .good-brand {
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 12px;
            color: #501414;
            width: 80px;
            height: 22px;
            background: linear-gradient(90deg, #f3c582, #fdeaa5);
            border-radius: 11px;
          }
          .shixun-brand {
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 12px;
            color: #252e54;
            width: 80px;
            height: 22px;
            background: linear-gradient(90deg, #c2dbff, #e5f0ff);
            border-radius: 11px;
          }
        }
      }
    }
  }

  .my-dialog {
    .my-dialog-title {
      padding: 0 48px;
      font-size: 20px;
      color: #204077;
      margin-bottom: 35px;
    }
    .dialog-info {
      font-size: 16px;
      color: #333333;
      line-height: 29px;
      padding: 40px 50px;
    }
    .my-dialog-tab {
      display: flex;
      justify-content: center;
      gap: 55px;
      .disabled {
        cursor: no-drop;
        color: #a8abb2;
        &:hover {
          color: #a8abb2;
        }
      }
      > div {
        font-size: 16px;
        color: #6b6a85;
        cursor: pointer;
        &:hover {
          color: #457aff;
        }
        &.active {
          color: #457aff;
          cursor: pointer;
          &:hover {
            color: #457aff;
          }
          &::after {
            content: "";
            display: block;
            width: 50%;
            height: 2px;
            margin: 17px auto 0;
            background: #3486e4;
          }
        }
      }
    }
    .my-dialog-content {
      display: flex;
      flex-direction: column;
      gap: 20px;
      padding: 20px 0 40px;
      > div {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 24px;
        &.flex-start {
          align-items: flex-start;
        }
        .item-label {
          width: 100px;
          text-align: right;
          font-size: 16px;
          color: #000000;
          .red {
            color: red;
            margin-right: 4px;
          }
        }
        .item-content {
          .tiao-box {
            width: 400px;
            display: flex;
            gap: 30px;
            > a {
              width: 120px;
              height: 60px;
              border-radius: 10px;
              background: #ecf3ff;
              display: flex;
              justify-content: center;
              align-items: center;
              box-sizing: border-box;
              cursor: pointer;
              &:hover {
                background: #ecf1fa;
                border: 2px solid #457aff;
              }
            }
          }
          :deep(.el-input) {
            width: 400px;
          }
          :deep(.el-textarea) {
            width: 400px;
          }
        }
      }
    }
  }
}
</style>